package Lee_code;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author blh
 * @date 2024年07月02日 10:46
 */
public class Lee_227_72 {
    public int calculate(String s) {

        Deque<Integer> deque = new LinkedList<>();
        int index = 0;
        StringBuilder sb = new StringBuilder(s);
        sb.insert(0, '+');
        s = sb.toString();
        int len = s.length();
        while (index < len) {

            if (s.charAt(index) == ' ') {
                index++;
            } else if (s.charAt(index) == '+') {
                StringBuilder temp = new StringBuilder();
                index++;
                while (index < len) {
                    if (Character.isDigit(s.charAt(index))) {
                        temp.append(s.charAt(index));
                        index++;
                    } else if (s.charAt(index) == ' ') {
                        index++;
                    } else {
                        break;
                    }
                }
                deque.push(Integer.parseInt(temp.toString()));
            } else if (s.charAt(index) == '-') {
                StringBuilder temp = new StringBuilder();
                index++;
                while (index < len) {
                    if (Character.isDigit(s.charAt(index))) {
                        temp.append(s.charAt(index));
                        index++;
                    } else if (s.charAt(index) == ' ') {
                        index++;
                    } else {
                        break;
                    }
                }
                deque.push(-Integer.parseInt(temp.toString()));
            } else if (s.charAt(index) == '*') {
                int before = deque.pop();
                StringBuilder temp = new StringBuilder();
                index++;
                while (index < len) {
                    if (Character.isDigit(s.charAt(index))) {
                        temp.append(s.charAt(index));
                        index++;
                    } else if (s.charAt(index) == ' ') {
                        index++;
                    } else {
                        break;
                    }
                }
                deque.push(before * Integer.parseInt(temp.toString()));
            } else if (s.charAt(index) == '/') {
                int before = deque.pop();
                StringBuilder temp = new StringBuilder();
                index++;
                while (index < len) {
                    if (Character.isDigit(s.charAt(index))) {
                        temp.append(s.charAt(index));
                        index++;
                    } else if (s.charAt(index) == ' ') {
                        index++;
                    } else {
                        break;
                    }
                }
                deque.push(before / Integer.parseInt(temp.toString()));
            }
        }
        return deque.stream().mapToInt(Integer::intValue).sum();
    }

}
